from re import I
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import os,time
from Ui_main import Ui_MainWindow
import pandas as pd
import random
from shutil import copyfile
import shutil,_thread
from zipencrypt import ZipFile

class MainView(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainView, self).__init__()
        self.main = Ui_MainWindow()
        self.main.setupUi(self)
        self.main.pushButton.clicked.connect(self.chooseProblemFile)
        self.main.pushButton_2.clicked.connect(self.chooseListeningFolder)
        self.main.pushButton_3.clicked.connect(self.chooseOutputFolder)
        self.main.pushButton_4.clicked.connect(self.genFiles)
        self.main.pushButton_5.clicked.connect(self.reset)
        self.problemFile=None
        self.listeningFolder=None
        self.outputFolder=None
        self.num=None


    # 选择题库
    def chooseProblemFile(self):
        self.problemFile = QtWidgets.QFileDialog.getOpenFileName(self, caption='选择文件',filter='Excels (*.xlsx *.csv)')[0]
        self.main.lineEdit.setText(self.problemFile)
        if self.problemFile:
            self.df = pd.read_excel(self.problemFile, engine='openpyxl')


    # 选择听力文件夹
    def chooseListeningFolder(self):
        self.listeningFolder = QtWidgets.QFileDialog.getExistingDirectory(self, caption='选择文件夹')
        self.main.lineEdit_2.setText(self.listeningFolder)
        if self.listeningFolder:
            self.listeningNames = [f for f in os.listdir(self.listeningFolder) if not f.startswith('.')]


    # 选择输出目录
    def chooseOutputFolder(self):
        self.outputFolder = QtWidgets.QFileDialog.getExistingDirectory(self, caption='选择文件夹')
        self.main.lineEdit_3.setText(self.outputFolder)

        self.tmpDir = os.path.join(self.outputFolder,'tmp')
        if not os.path.exists(self.tmpDir):
            os.mkdir(self.tmpDir)

    def check(self):
        self.num = int(self.main.lineEdit_4.text() or 0)
        if not self.problemFile or not self.listeningFolder or not self.outputFolder or not self.num:
            self.message('有信息未输入！')
            return False

        if self.df.shape[0] < self.num:
            self.message('题库数量小于学生数量！')
            return False

        if len(self.listeningNames) < self.num:
            self.message('听力材料小于学生数量！')
            return False

        return True

    # 输出打包文件
    def genFiles(self):
        if not self.check():
            return

        if not os.path.exists(self.tmpDir):
            os.mkdir(self.tmpDir)

        # 输出num个题目列表的excel文件
        len = self.df.shape[0]
        problemIndex = list(range(len))
        random.shuffle(problemIndex)
        problemTruple = [(problemIndex[3*x],problemIndex[3*x+1],problemIndex[3*x+2]) for x in range(self.num)]
        print('随机的序号：',problemTruple)

        self.prepareListening()
        self.genPasswords()
        i = 0
        for t in problemTruple:

            self.updateStatusBar(f'输出目录：{self.outputFolder}        已完成{i}/{self.num}')

            QtCore.QCoreApplication.processEvents()

            # 抽取三道题
            curProblemsSlice = self.df.iloc[[t[0],t[1],t[2]],:]
            curProblems = pd.DataFrame(curProblemsSlice)
            curProblems['序号'] = [1,2,3]

            # 输出答案
            ansPath = os.path.join(self.tmpDir,'题目答案.xlsx')
            curProblems.to_excel(ansPath,index=False)

            # 输出三道题
            excelPath = os.path.join(self.tmpDir,'题目列表.xlsx')
            curProblems.iloc[:,[0,1,2,3]].to_excel(excelPath,index=False)

            #拷贝听力
            copyfile(self.listeningPathsShuffled[i],os.path.join(self.tmpDir,'听力题.mp3'))

            # 压缩
            self.zip(f'题库{i+1}.zip',self.passwordList[i])
            i+=1
            time.sleep(0.1)

            # 清除

        self.main.statusbar.clearMessage()
        # self.main.tips.setText('')
        self.df['选择']=''
        self.df['选择'][problemIndex[:3*self.num]] = '已选择'
        self.df.to_excel(os.path.join(self.outputFolder,'已做标记的题库.xlsx'),index=False)

        shutil.rmtree(self.tmpDir)

        print('输出成功')
        self.message(f'输出成功！目录是：{self.outputFolder}')

    # 获取打乱后的听力path
    def prepareListening(self):
        index = list(range(self.num))
        random.shuffle(index)
        self.listeningPathsShuffled = [os.path.join(self.listeningFolder,self.listeningNames[x]) for x in index ]

    def zip(self,name,password):
        fileNameList = os.listdir(self.tmpDir)
        srcFiles = [os.path.join(self.tmpDir,name) for name in fileNameList]

        distPath = os.path.join(self.outputFolder,name)
        # pyminizip.compress_multiple(srcFiles,[],distPath, str(password), int(4))

        with ZipFile(distPath, mode="w") as f:
            for file in srcFiles:
                f.write(file,arcname=os.path.basename(file), pwd=bytes(str(password),encoding='utf8'))



    # 随机生成并保存密码
    def genPasswords(self):
        self.passwordList=[]
        for i in range(self.num):
            self.passwordList.append(random.randint(100000,999999))

        content = [f'题库{x+1}的密码：{self.passwordList[x]}' for x in range(self.num)]
        with open(os.path.join(self.outputFolder,'密码.txt'),'w') as f:
            f.write('\n'.join(content))

    # 重置
    def reset(self):
        self.problemFile=''
        self.outputFolder=''
        self.listeningFolder=''
        self.main.lineEdit.setText(self.problemFile)
        self.main.lineEdit_2.setText(self.listeningFolder)
        self.main.lineEdit_3.setText(self.outputFolder)

    def message(self,msg):
        msgBox = QtWidgets.QMessageBox()
        msgBox.setText(msg)
        msgBox.exec()

    def updateStatusBar(self,text):
        self.main.statusbar.showMessage(text)
        # self.main.tips.setText('text')


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    m = MainView()
    m.show()
    sys.exit(app.exec_())
